<?php

namespace App\Services;

use App\Exceptions\ApiException;
use GuzzleHttp\Client;

class OpenPlatformService extends Service
{
    protected $accessToken;
    protected $appId;
    protected $appSecret;
    protected $authorizerInfo;
    protected $baseUri;
    protected $httpClient;
    protected $openId;

    public function __construct()
    {
        $this->appId = env('WECHAT_OPEN_PLATFORM_APPID');
        $this->appSecret = env('WECHAT_OPEN_PLATFORM_SECRET');
        $this->baseUri = 'https://api.weixin.qq.com';
        $this->httpClient = new Client(['base_uri' => $this->baseUri]);
    }

    public function getAuthorizer()
    {
        return $this->authorizerInfo;
    }

    protected function getAuthorizerInfo()
    {
        $response = $this->httpClient->request(
            'GET',
            '/sns/userinfo',
            [
                'query' => [
                    'access_token' => $this->accessToken,
                    'openid' => $this->openId
                ]
            ]
        );
        $response_obj = json_decode($response->getBody()->getContents(), true);
        if (isset($response_obj['errcode']) && $response_obj['errcode'] != 0) {
            throw new ApiException($response_obj['errmsg'], $response_obj['errcode']);
        }
        $this->authorizerInfo = $response_obj;
    }

    public function handleAuthorize($authCode)
    {
        $response = $this->httpClient->request(
            'GET',
            '/sns/oauth2/access_token',
            [
                'query' => [
                    'appid' => $this->appId,
                    'secret' => $this->appSecret,
                    'code' => $authCode,
                    'grant_type' => 'authorization_code'
                ]
            ]
        );
        $response_obj = json_decode($response->getBody()->getContents(), true);
        if (isset($response_obj['errcode']) && $response_obj['errcode'] != 0) {
            throw new ApiException($response_obj['errmsg'], $response_obj['errcode']);
        }
        $this->accessToken = $response_obj['access_token'];
        $this->openId = $response_obj['openid'];
        $this->getAuthorizerInfo();
    }
}